package cn.edu.lcvc.ebuy_23rj2.web.filter;

import cn.edu.lcvc.ebuy_23rj2.model.Admin;
import cn.edu.lcvc.ebuy_23rj2.service.AdminService;
import com.sun.org.apache.xpath.internal.objects.XObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginForAdminIntegerceptor extends HandlerInterceptorAdapter {
    @Autowired
    private AdminService adminService;
    /**
     * 在执行被拦截的controller之前执行。true不拦截，false拦截。
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        boolean result=true;//不拦截
        //获取当前用户信息
        HttpSession session=request.getSession();
        Admin admin=(Admin)session.getAttribute("admin");
        if (admin!=null){//已经登陆
            if (!adminService.login(admin.getUsername(),admin.getPassword())){
                session.removeAttribute("admin");
                result=false;//拒绝登陆
            }
        }else {//没有登陆
            result=false;
        }
        if (result==false){//拒绝访问后，回到登陆页
            String path = request.getContextPath();
            // 获得项目完全路径（假设你的项目叫ebuy_2023rj4，那么获得到的地址就是http://localhost:8081/ebuy_2023rj4/）:
            String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+ path + "/";
            response.sendRedirect(basePath+"jsp/backstage/login.jsp");
        }
        return result;
    }
}
